<template>
  <div class="tenant-management">

    <div class="page-content">
      <!-- 租户管理 -->
      <el-card class="tenant-card">
        <template #header>
          <div class="card-header">
            <span>租户管理</span>
            <el-space>
              <el-button type="primary" @click="handleCreateTenant">
                <el-icon><Plus /></el-icon>
                新增租户
              </el-button>
              <el-button @click="handleTenantPackage">
                <el-icon><Setting /></el-icon>
                租户套餐
              </el-button>
            </el-space>
          </div>
        </template>

        <!-- 搜索表单 -->
        <el-form
          v-show="showSearch"
          ref="queryRef"
          :model="queryParams"
          :inline="true"
          label-width="80px"
          class="search-form"
        >
          <el-form-item label="租户编号" prop="tenantId">
            <el-input 
              v-model="queryParams.tenantId" 
              placeholder="请输入租户编号" 
              clearable 
              @keyup.enter="handleQuery" 
            />
          </el-form-item>
          <el-form-item label="联系人" prop="contactUserName">
            <el-input 
              v-model="queryParams.contactUserName" 
              placeholder="请输入联系人" 
              clearable 
              @keyup.enter="handleQuery" 
            />
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input 
              v-model="queryParams.contactPhone" 
              placeholder="请输入联系电话" 
              clearable 
              @keyup.enter="handleQuery" 
            />
          </el-form-item>
          <el-form-item label="企业名称" prop="companyName">
            <el-input 
              v-model="queryParams.companyName" 
              placeholder="请输入企业名称" 
              clearable 
              @keyup.enter="handleQuery" 
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 数据表格 -->
        <el-table
          v-loading="loading"
          :data="tenantList"
          border
          @row-click="handleRowClick"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="租户编号" align="center" prop="tenantId" width="120" />
          <el-table-column label="企业名称" align="center" prop="companyName" width="150" show-overflow-tooltip />
          <el-table-column label="联系人" align="center" prop="contactUserName" width="100" />
          <el-table-column label="联系电话" align="center" prop="contactPhone" width="120" />
          <el-table-column label="域名" align="center" prop="domain" width="150" show-overflow-tooltip />
          <el-table-column label="套餐编号" align="center" prop="packageId" width="100" />
          <el-table-column label="状态" align="center" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status === '1' ? 'success' : 'danger'">
                {{ row.status === '1' ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
          <el-table-column label="操作" align="center" fixed="right" width="220">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEditTenant(row)">编辑</el-button>
              <el-button type="warning" link @click="handleSyncPackage(row)">同步套餐</el-button>
              <el-button type="danger" link @click="handleDeleteTenant(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-show="pagination.total > 0"
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageChange"
          @current-change="handlePageChange"
        />
      </el-card>
    </div>

    <!-- 新增/编辑租户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="tenantFormRef"
        :model="tenantForm"
        :rules="tenantRules"
        label-width="100px"
      >
        <el-form-item label="租户编号" prop="tenantId">
          <el-input 
            v-model="tenantForm.tenantId" 
            placeholder="请输入租户编号"
            :disabled="!!tenantForm.id"
          />
        </el-form-item>
        <el-form-item label="企业名称" prop="companyName">
          <el-input v-model="tenantForm.companyName" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactUserName">
          <el-input v-model="tenantForm.contactUserName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="tenantForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="域名" prop="domain">
          <el-input v-model="tenantForm.domain" placeholder="请输入域名" />
        </el-form-item>
        <el-form-item label="租户套餐" prop="packageId">
          <el-select v-model="tenantForm.packageId" placeholder="请选择租户套餐" style="width: 100%">
            <el-option
              v-for="item in packageList"
              :key="item.packageId"
              :label="item.packageName"
              :value="item.packageId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="tenantForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Setting, Search, Refresh } from '@element-plus/icons-vue';
import { 
  listTenant, 
  getTenant,
  addTenant,
  updateTenant,
  delTenant, 
  syncTenantPackage 
} from '@/api/tenant/tenant';
import { selectTenantPackage } from '@/api/tenant/package';

defineOptions({
  name: 'TenantManagement',
});

const router = useRouter();

// 响应式数据
const loading = ref(false);
const showSearch = ref(true);
const tenantList = ref<any[]>([]);
const packageList = ref<any[]>([]);
const dialogVisible = ref(false);
const dialogTitle = ref('');
const queryRef = ref();
const tenantFormRef = ref();

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  tenantId: undefined as string | undefined,
  contactUserName: undefined as string | undefined,
  contactPhone: undefined as string | undefined,
  companyName: undefined as string | undefined,
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

// 租户表单
const tenantForm = reactive({
  id: undefined as number | undefined,
  tenantId: '',
  companyName: '',
  contactUserName: '',
  contactPhone: '',
  domain: '',
  packageId: undefined as number | undefined,
  status: '1',
});

// 表单验证规则
const tenantRules = {
  tenantId: [{ required: true, message: '租户编号不能为空', trigger: 'blur' }],
  companyName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
  contactUserName: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '联系电话不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  packageId: [{ required: true, message: '请选择租户套餐', trigger: 'change' }],
};

// 方法
const handleQuery = () => {
  queryParams.pageNum = 1;
  pagination.current = 1;
  getList();
};

const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    tenantId: undefined,
    contactUserName: undefined,
    contactPhone: undefined,
    companyName: undefined,
  });
  pagination.current = 1;
  getList();
};

const getList = async () => {
  loading.value = true;
  try {
    const response = await listTenant({
      ...queryParams,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    });
    tenantList.value = response.rows || [];
    pagination.total = response.total || 0;
  } catch (error) {
    console.error('获取租户列表失败:', error);
    ElMessage.error('获取租户列表失败');
  } finally {
    loading.value = false;
  }
};

const getPackageList = async () => {
  try {
    const response = await selectTenantPackage();
    packageList.value = response.data || [];
  } catch (error) {
    console.error('获取套餐列表失败:', error);
  }
};

const handleCreateTenant = () => {
  resetForm();
  dialogVisible.value = true;
  dialogTitle.value = '新增租户';
  getPackageList();
};

const handleEditTenant = async (row: any) => {
  resetForm();
  try {
    const response = await getTenant(row.id);
    Object.assign(tenantForm, response.data);
    dialogVisible.value = true;
    dialogTitle.value = '编辑租户';
    getPackageList();
  } catch (error) {
    console.error('获取租户详情失败:', error);
    ElMessage.error('获取租户详情失败');
  }
};

const handleDeleteTenant = (row: any) => {
  ElMessageBox.confirm(
    `是否确认删除租户编号为"${row.tenantId}"的数据项？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    return delTenant(row.id);
  }).then(() => {
    getList();
    ElMessage.success('删除成功');
  }).catch(() => {
    // 用户取消删除
  });
};

const handleSyncPackage = (row: any) => {
  ElMessageBox.confirm(
    `是否确认同步租户套餐租户编号为"${row.tenantId}"的数据项？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
    }
  ).then(() => {
    return syncTenantPackage(row.tenantId, row.packageId);
  }).then(() => {
    ElMessage.success('同步成功');
  }).catch(() => {
    // 用户取消同步
  });
};

const handleTenantPackage = () => {
  router.push('/tenant/package');
};

const handlePageChange = () => {
  queryParams.pageNum = pagination.current;
  queryParams.pageSize = pagination.pageSize;
  getList();
};

const handleRowClick = (row: any) => {
  console.log('点击行:', row);
};

const handleSubmit = () => {
  tenantFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const submitFunc = tenantForm.id ? updateTenant : addTenant;
      submitFunc(tenantForm).then(() => {
        ElMessage.success(tenantForm.id ? '修改成功' : '新增成功');
        dialogVisible.value = false;
        getList();
      }).catch((error: any) => {
        console.error('提交失败:', error);
        ElMessage.error('操作失败');
      });
    }
  });
};

const handleDialogClose = () => {
  resetForm();
};

const resetForm = () => {
  Object.assign(tenantForm, {
    id: undefined,
    tenantId: '',
    companyName: '',
    contactUserName: '',
    contactPhone: '',
    domain: '',
    packageId: undefined,
    status: '1',
  });
  tenantFormRef.value?.resetFields();
};

// 生命周期
onMounted(() => {
  console.log('[TenantManagement] 组件已挂载');
  getList();
});
</script>

<style scoped>
.tenant-management {
  padding: 20px;
}


.page-content {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.tenant-card {
  border: none;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>
